import axios from 'axios'
import store from "@/store";
import router from "@/router";

const logout = () => {
    router.push('/')
    store.commit('logout')
}

const instance = axios.create({
        // baseURL: 'http://172.31.7.185:8080/',
        // baseURL: 'http://172.31.0.189:8080/',
        baseURL: 'http://localhost:8080/',
        timeout: 5000,
        headers: {
            'Content-Type': 'application/json;charset=UTF-8',
            'Accept': 'application/json;charset=UTF-8'
        },
        transformRequest: [function (data) {
            return JSON.stringify(data);
        }],
        transformResponse: [function (data) {
            try {
                return JSON.parse(data);
            } catch (error) {
                return data;
            }
        }]
    }
)
instance.interceptors.request.use(
    config => {
        if (store.state.token) {
            config.headers['token'] = store.state.token;
            config.headers['headers'] = {'Content-Type': 'application/json'};
        }
        return config
    },
    error => {
        console.log(error)
        return Promise.reject(error)
    }
)

// 添加响应拦截器
instance.interceptors.response.use(
    response => {
        return response;
    },
    error => {
        if (error.response && error.response.status === 401) {
            logout();
        }
        return Promise.reject(error);
    }
)

export const ipost = (url, data, config) => {
    return instance.post(url, data, config)
}
export const iget = (url, data) => {
    return instance.get(url, {
        method: 'get',
        params: data
    })
}
export const iput = (url, data) => {
    return instance.put(url, data,
        {
            method: 'put',
            params: data,
        }
    )
}
export const idel = (url, config) => {
    return instance.delete(url, config)
}

export default instance
